/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ugd.controller;

import edu.ugd.domain.EncodingForm;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 *
 * @author User
 */
@Controller
@SessionAttributes({"encodingForm"})
public class UrlController extends Base {

    @RequestMapping(value = "/url*", method = RequestMethod.GET)
    public String doHtml(
            HttpServletRequest req,
            ModelMap model) {
        HttpSession session = req.getSession();
        session.setAttribute("encodingForm", new EncodingForm());
        model.put("encodings", getEncodings());
        return "url";
    }

    @RequestMapping(value = "/url*", method = RequestMethod.POST)
    public String submitHtml(
            HttpServletRequest request,
            HttpServletResponse response,
            @ModelAttribute("encodingForm") EncodingForm encodingForm,
            @RequestParam String action,
            ModelMap model) throws UnsupportedEncodingException {
        if (encodingForm != null) {
            String userInput = encodingForm.getUserInput();
            if (userInput != null && !userInput.equals("")) {
                if (action.equals("encode")) {
                    String encoded = URLEncoder.encode(userInput, encodingForm.getEncoding());
                    encodingForm.setGeneratedOutput(encoded);
                } else {
                    String decoded = URLDecoder.decode(userInput, encodingForm.getEncoding());
                    encodingForm.setGeneratedOutput(decoded);
                }
            }
        }
        model.put("encodings", getEncodings());
        return "url";
    }

}
